package com.sy.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sy.constant.JwtClaimsConstant;
import com.sy.dto.*;
import com.sy.pojo.Employee;
import com.sy.pojo.User;
import com.sy.properties.JwtProperties;
import com.sy.result.PageResult;
import com.sy.result.Result;
import com.sy.service.UserService;
import com.sy.utils.HuYiCloudSMS;
import com.sy.utils.JwtUtil;
import com.sy.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = "用户相关接口")
@RestController("commonUserController")
@RequestMapping("/user/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;


    @Autowired
    private StringRedisTemplate redisTemplate;



    @GetMapping("/doExistPhone")
    @ApiOperation("查询手机号是否存在")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "要验证的手机号" ,name = "phone",
                    required = true,
                    dataTypeClass =String.class)
    })
    public Result<String> doExistPhone(String phone){
        //打印请求数据日志
        log.info("手机号为：{}",phone);
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone,phone);
        User user = userService.getOne(queryWrapper);
        if(user==null){
            return Result.success();
        }else {
            return Result.error("手机号已经存在");
        }
    }
    @GetMapping("/doExistUsername")
    @ApiOperation("查询用户名是否存在")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "要验证的用户名",name = "username",
                    required = true,
                    dataTypeClass =String.class)
    })
    public Result<String> doExistUsername(String username){
        //打印请求数据日志
        log.info("用户名为：{}",username);
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);
        User user = userService.getOne(queryWrapper);
        if(user==null){
            return Result.success();
        }else {
            return Result.error("用户名已经存在");
        }
    }


    /**
     * 注册用户（新增）
     * @param userRegisterDTO
     * @return
     */
    @PostMapping("save")
    @ApiOperation("用户端注册")
    public Result save(@RequestBody UserRegisterDTO userRegisterDTO) {
        log.info("用户名为：{}",userRegisterDTO);
        try {
            //调用业务处理逻辑
            User user=new User();
            BeanUtils.copyProperties(userRegisterDTO,user);
            //设置默认密码
            user.setPassword(DigestUtils.md5DigestAsHex(userRegisterDTO.getPassword().getBytes()));
            //设置创建时间
            user.setCreatetime(LocalDateTime.now());
            userService.save(user);
        } catch (BeansException e) {
            throw new RuntimeException("注册失败");
        }
        return Result.success("注册成功");
    }

    @ApiOperation("用户端登录")
    @PostMapping("login")
    public Result login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("登录请求：{}" + userLoginDTO);
        //
        User user=userService.login(userLoginDTO);
        Map<String,Object> objectMap=new HashMap<>();
        objectMap.put(JwtClaimsConstant.USER_ID,user.getUid());
        String token= JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getUserTtl(),objectMap);
        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtils.copyProperties(user,userLoginVO);
        userLoginVO.setToken(token);
        return Result.success(userLoginDTO);
    }

    /**
     * 用户端发送验证码
     * @param phone
     * @return
     */
    @ApiOperation("用户端发送验证码")
    @GetMapping("sendCode")
    public Result sendCode(String phone){
        //发送验证码
//        String phoneCode= HuYiCloudSMS.sendSMS(phone);
        String phoneCode="123456";
        System.out.println(phoneCode);
        //验证码保存到redis缓存中
        redisTemplate.opsForValue().set(phone + "_" + phoneCode,phoneCode,5,TimeUnit.MINUTES);
        if(phoneCode!=null){
            return Result.success();
        }else {
            return Result.error("验证码发送失败");
        }
    }

    @ApiOperation("用户端登录02")
    @PostMapping("login02")
    public Result login02(@RequestBody UserLoginDTO02 userLoginDTO02){
        log.info("登录请求：{}" + userLoginDTO02);
        //获取redis中存储的验证码
        String redisCode = redisTemplate.opsForValue().get(userLoginDTO02.getPhone() + "_" + userLoginDTO02.getCode());
        //判断验证码是否一致
        if(redisCode!=null&&redisCode.equals(userLoginDTO02.getCode())){
            //验证码正确
            User user=userService.login02(userLoginDTO02);
            Map<String,Object> objectMap=new HashMap<>();
            objectMap.put(JwtClaimsConstant.USER_ID,user.getUid());
            String token= JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getUserTtl(),objectMap);
            UserLoginVO userLoginVO = new UserLoginVO();
            BeanUtils.copyProperties(user,userLoginVO);
            userLoginVO.setToken(token);
            return Result.success(userLoginDTO02);
        }else {
            return Result.error("验证码错误");
        }


    }

}
